// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

// 引入阿里云OCR SDK
const Core = require("@alicloud/pop-core");

// 创建OCR客户端
function createOcrClient() {
  const accessKeyId = process.env.ALIYUN_ACCESS_KEY_ID;
  const accessKeySecret = process.env.ALIYUN_ACCESS_KEY_SECRET;

  if (!accessKeyId || !accessKeySecret) {
    throw new Error("缺少阿里云访问密钥配置");
  }

  return new Core({
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    endpoint: "https://ocr-api.cn-hangzhou.aliyuncs.com",
    apiVersion: "2021-07-07",
  });
}

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { imageUrl } = event;

    if (!imageUrl) {
      return {
        code: 400,
        message: "缺少图片URL参数",
        data: null,
      };
    }

    // 创建OCR客户端
    const client = createOcrClient();

    // 调用OCR识别接口
    const params = {
      Url: imageUrl,
    };

    const requestOption = {
      method: "POST",
    };

    const response = await client.request(
      "RecognizeBasic",
      params,
      requestOption
    );

    console.log("OCR API响应:", response);

    // 检查响应格式
    if (response && response.Data) {
      // 如果Data是字符串，需要解析
      let ocrData = response.Data;
      if (typeof ocrData === "string") {
        try {
          ocrData = JSON.parse(ocrData);
        } catch (e) {
          console.error("解析OCR数据失败:", e);
          throw new Error("OCR数据格式错误");
        }
      }

      return {
        code: 0,
        message: "识别成功",
        data: ocrData,
      };
    } else {
      throw new Error("OCR API返回数据格式错误");
    }
  } catch (error) {
    console.error("OCR识别错误:", error);
    return {
      code: 500,
      message: `识别失败: ${error.message}`,
      data: null,
    };
  }
};
